﻿#include "Mapper_Device.h"

#include "DataBaseConnector.h"
#include "MapperTool.h"

#include "qvariant.h"

Mapper_Device::Mapper_Device()
{
setObjectName(getClassNameFirstLow<Mapper_Device>());
}

Mapper_Device::~Mapper_Device()
{}

bool Mapper_Device::isVaildDevice(uint deviceId)
{
  QString mysql="SELECT "+string_device_id+
                " FROM `"+string_dataBaseName_device+
                "` WHERE "+string_device_id+"='%1';";
  mysql=mysql.arg(deviceId);
  QSqlQuery query=dataBaseConnector->exec(mysql);
  return query.lastError().type()==QSqlError::NoError&&query.size()>0?true:false;
}

QList<uint> Mapper_Device::getDevicesByUserName(QString userName)
{
  QString mysql="SELECT "+string_device_id+
                " FROM `"+string_dataBaseName_user+"`,`"+string_dataBaseName_map_user_device+
                "` WHERE `"+string_dataBaseName_user+"`."+string_user_name+"='"+userName+"' AND `"+
                string_dataBaseName_user+"`."+string_user_id+"=`"+string_dataBaseName_map_user_device+"`."+string_user_id+";";
  QSqlQuery query=dataBaseConnector->exec(mysql);
  if(query.lastError().type()==QSqlError::NoError)
    {
      QList<uint> result;
      while (query.next())
        {
          result.append(query.value(string_device_id).toUInt());
        }
      return result;
    }
  else
    {
      return QList<uint>();
    }
}

QList<uint> Mapper_Device::getDevicesByUserId(uint user_id)
{
  QString mysql="SELECT "+string_device_id+
      " FROM `"+string_dataBaseName_map_user_device+
      "` WHERE "+string_user_id+"='"+QString::number(user_id)+"';";
  QSqlQuery query=dataBaseConnector->exec(mysql);
  if(query.lastError().type()==QSqlError::NoError)
    {
      QList<uint> result;
      while (query.next())
        {
          result.append(query.value(string_device_id).toUInt());
        }
      return result;
    }
  else
    {
      return QList<uint>();
    }
}

DataBaseConnector* Mapper_Device::getDataBaseConnector()
{
  return dataBaseConnector;
}

void Mapper_Device::setDataBaseConnector(DataBaseConnector* dataBaseConnector)
{
  this->dataBaseConnector=dataBaseConnector;
  printInjection(this,dataBaseConnector);
}

void Mapper_Device::objectAutoInjection(QHash<QString, QObject *> *objMap)
{
  setDataBaseConnector(getObjFromMap<DataBaseConnector>(objMap));
}
